package com.aizhixin.lab.post.server;

import com.aizhixin.lab.common.core.DataValidity;
import com.aizhixin.lab.common.core.PageData;
import com.aizhixin.lab.common.core.PageUtil;
import com.aizhixin.lab.common.domain.PageDomain;
import com.aizhixin.lab.common.dto.SortDTO;
import com.aizhixin.lab.common.utils.PageJdbcUtil;
import com.aizhixin.lab.post.data.PostData;
import com.aizhixin.lab.post.data.PostSkillData;
import com.aizhixin.lab.post.data.SkillPointsData;
import com.aizhixin.lab.post.domain.PostDomain;
import com.aizhixin.lab.post.domain.PostSkillDomain;
import com.aizhixin.lab.post.domain.QueryPostDomain;
import com.aizhixin.lab.post.domain.SkillPointsDomain;
import com.aizhixin.lab.post.entity.*;
import com.aizhixin.lab.post.repository.PostRepository;
import com.aizhixin.lab.post.repository.TransferabilityRepository;
import com.aizhixin.lab.project.template.domain.PostInfoDomain;
import com.aizhixin.lab.project.template.domain.ProjectCourseDomain;
import com.aizhixin.lab.project.template.domain.ProjectDomain;
import com.aizhixin.lab.project.template.entity.Project;
import com.aizhixin.lab.project.template.entity.ProjectPost;
import com.aizhixin.lab.task.domain.ReleaseTaskDomain;
import javafx.geometry.Pos;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;

@Slf4j
@Service
@Transactional
public class PostService {
    @Autowired
    private PostRepository postRepository;
    @Autowired
    private PostSkillService skillService;
    @Autowired
    private SkillPointsService pointsService;
    @Autowired
    private PageJdbcUtil pageJdbcUtil;
    @Autowired
    private TransferabilityRepository transferabilityRepository;

    public String save(PostDomain domain) {
        Post post = new Post();
        Boolean isNew = false;
        List<PostSkill> postSkillList = new ArrayList<>();
        List<SkillPoints> skillPointsList = new ArrayList<>();
        if (StringUtils.isEmpty(domain.getId())) {
            domain.setId(UUID.randomUUID().toString());
            isNew = true;
        }
        BeanUtils.copyProperties(domain, post);
        List<Transferability> transferabilityList = new ArrayList<>();
        int i = 1;
        for (String s : domain.getTransferabilityList()) {
            Transferability transferability = new Transferability();
            transferability.setPostId(domain.getId());
            transferability.setId(UUID.randomUUID().toString());
            transferability.setName(s);
            transferability.setNo(i);
            transferabilityList.add(transferability);
            i++;
        }
        post.setDeleteFlag(DataValidity.VALID.getState());
        post.setCreatedDate(new Date());
        for (PostSkillDomain skillDomain : domain.getSkillDomainList()) {
            PostSkill postSkill = new PostSkill();
            BeanUtils.copyProperties(skillDomain, postSkill);
            postSkill.setId(UUID.randomUUID().toString());
            postSkill.setCreatedDate(new Date());
            postSkill.setPostId(domain.getId());
            postSkill.setDeleteFlag(DataValidity.VALID.getState());
            postSkillList.add(postSkill);
            for (SkillPointsDomain pointsDomain : skillDomain.getPointsDomainList()) {
                SkillPoints skillPoints = new SkillPoints();
                BeanUtils.copyProperties(pointsDomain, skillPoints);
                skillPoints.setId(UUID.randomUUID().toString());
                skillPoints.setSkillId(postSkill.getId());
                skillPoints.setDeleteFlag(DataValidity.VALID.getState());
                skillPointsList.add(skillPoints);
            }
        }
        if (isNew) {
            skillService.save(postSkillList);
            pointsService.save(skillPointsList);
            postRepository.save(post);
            transferabilityRepository.save(transferabilityList);
        } else {
            List<PostSkill> postSkill = skillService.findPostSkill(domain.getId());
            for (PostSkill skill : postSkill) {
                pointsService.delete(skill.getId());
            }
            transferabilityRepository.deleteByPostId(domain.getId());
            skillService.delete(post.getId());
            skillService.save(postSkillList);
            pointsService.save(skillPointsList);
            postRepository.save(post);
            transferabilityRepository.save(transferabilityList);
        }
        return "OK";
    }

    public List<Post> save(List<Post> postList) {
        return postRepository.save(postList);
    }

    RowMapper<PostDomain> postDomainRowMapper = new RowMapper<PostDomain>() {

        @Override
        public PostDomain mapRow(ResultSet rs, int rowNum) throws SQLException {

            PostDomain domain = new PostDomain();
            domain.setId(rs.getString(1));
            domain.setBusinessId(rs.getString(2));
            domain.setPostName(rs.getString(3));
            domain.setPostCoverUrl(rs.getString(4));
            return domain;
        }
    };

    public Map<String, Object> findPost1(QueryPostDomain domain) {
        String sql = "SELECT id,business_id,post_name,post_cover_url FROM p_post WHERE delete_flag=0 ";
        String countSql = "SELECT count(id) FROM p_post WHERE delete_flag=0 ";
        if (!StringUtils.isEmpty(domain.getPostName())) {
            sql += " AND post_name LIKE '%" + domain.getPostName() + "%'";
            countSql += " AND post_name LIKE '%" + domain.getPostName() + "%'";
        }
        if (domain.getPostType() != null && domain.getPostType() != 0) {
            sql += " AND post_type =" + domain.getPostType();
            countSql += " AND post_type =" + domain.getPostType();
        }
        if (domain.getStatus() != null && domain.getStatus() != 0) {
            sql += " AND post_status=" + domain.getStatus();
            countSql += " AND post_status=" + domain.getStatus();
        }
        if (!StringUtils.isEmpty(domain.getBusinessId())){
            sql+="AND business_id='"+domain.getBusinessId()+"'";
            countSql+="AND business_id='"+domain.getBusinessId()+"'";
        }
        List<SortDTO> sort = new ArrayList<SortDTO>();
        SortDTO dto = new SortDTO();
        dto = new SortDTO();
        dto.setKey("created_date");
        dto.setAsc(false);
        sort.add(dto);
       return pageJdbcUtil.getPageInfor(domain.getPageSize(),domain.getPageNumber(),postDomainRowMapper,sort,sql,countSql);
    }

    public PageData<PostDomain> findPost(QueryPostDomain domain) {
        Pageable pageable = PageUtil.createRequestAndSortType(domain.getPageNumber(), domain.getPageSize(), "desc", "createdDate");
        Page<Post> projectPage = null;
        if (StringUtils.isEmpty(domain.getPostName())) {
            //已发布
            if (domain.getPostType() != null && domain.getPostType() != 0) {
                //已选类型
                if (domain.getStatus() != null && domain.getStatus() != 0) {
                    projectPage = postRepository.findByPostTypeAndPostStatusAndDeleteFlag(pageable, domain.getPostType(), domain.getStatus(), DataValidity.VALID.getState());
                    //未选类型
                } else {
                    projectPage = postRepository.findByPostTypeAndDeleteFlag(pageable, domain.getPostType(), DataValidity.VALID.getState());
                }
            }
            //未发布
            else {
                //已选类型
                if (domain.getStatus() != null && domain.getStatus() != 0) {
                    projectPage = postRepository.findByPostStatusAndDeleteFlag(pageable, domain.getStatus(), DataValidity.VALID.getState());
                    //未选类型
                } else {
                    projectPage = postRepository.findByDeleteFlag(pageable, DataValidity.VALID.getState());
                }
            }
        }
        //名字不为空
        else {
            String name = "%" + domain.getPostName() + "%";
            if (domain.getPostType() != null && domain.getPostType() != 0) {
                //已选类型
                if (domain.getStatus() != null && domain.getStatus() != 0) {
                    projectPage = postRepository.findByPostTypeAndPostStatusAndPostNameIsLikeAndDeleteFlag(pageable, domain.getPostType(), domain.getStatus(), name, DataValidity.VALID.getState());
                    //未选类型
                } else {
                    projectPage = postRepository.findByPostTypeAndPostNameIsLikeAndDeleteFlag(pageable, domain.getPostType(), name, DataValidity.VALID.getState());
                }
            }
            //未发布
            else {
                if (domain.getStatus() != null && domain.getStatus() != 0) {
                    projectPage = postRepository.findByPostStatusAndPostNameAndDeleteFlag(pageable, domain.getStatus(), name, DataValidity.VALID.getState());
                    //未选类型
                } else {
                    projectPage = postRepository.findByPostNameIsLike(pageable, name);
                }
            }
        }
        PageDomain pageDomain = new PageDomain();
        pageDomain.setPageSize(projectPage.getSize());
        pageDomain.setPageNumber(projectPage.getNumber());
        pageDomain.setTotalElements(projectPage.getTotalElements());
        pageDomain.setTotalPages(projectPage.getTotalPages());
        List<PostDomain> projectDomains = new ArrayList<>();
        for (Post p : projectPage.getContent()) {
            PostDomain postDomain = new PostDomain();
            BeanUtils.copyProperties(p, postDomain);
            projectDomains.add(postDomain);
        }

        PageData<PostDomain> pageData = new PageData<>();

        pageData.setData(projectDomains);
        pageData.setPage(pageDomain);
        return pageData;
    }

    public List<Post> findList(List<String> idList) {
        return postRepository.findAll(idList);
    }

    public Post deletePost(String id) {
        Post post = postRepository.findOne(id);
        post.setDeleteFlag(DataValidity.INVALID.getState());
        return postRepository.save(post);
    }

    public PostData findPostInfo(String id) {
        PostData postData = new PostData();
        Post post = postRepository.findOne(id);
        BeanUtils.copyProperties(post, postData);
        List<PostSkillData> postSkillListData = skillService.findPostSkillListData(id);
        if (postSkillListData.size() > 0) {
            for (int i = 0; i < postSkillListData.size(); i++) {
                List<SkillPointsData> skillPointsList = pointsService.findSkillPointsList(postSkillListData.get(i).getId());
                postSkillListData.get(i).setPointsDomainList(skillPointsList);
            }
        }
        List<String> list = new ArrayList<>();
        List<Transferability> transferabilityList = transferabilityRepository.findByPostIdOrderByNoAsc(id);
        transferabilityList.forEach(transferability -> {
            list.add(transferability.getName());
        });
        postData.setTransferabilityList(list);
        postData.setPostSkillData(postSkillListData);
        return postData;
    }

    RowMapper<ProjectDomain> projectDomainRowMapper = new RowMapper<ProjectDomain>() {

        @Override
        public ProjectDomain mapRow(ResultSet rs, int rowNum) throws SQLException {

            ProjectDomain domain = new ProjectDomain();
            domain.setId(rs.getString("id"));
            domain.setProjectName(rs.getString("project_name"));
            return domain;
        }
    };

    public List<ProjectDomain> findProjectByPostId(String postId) {
        String sql = "SELECT tp.id,tp.project_name FROM t_project_post tpp LEFT JOIN t_project tp ON tpp.project_id=tp.id WHERE tpp.post_id= '" + postId + "' and tp.delete_flag=0 ORDER BY tp.created_date ASC";
        return pageJdbcUtil.getInfo(sql, projectDomainRowMapper);
    }

    RowMapper<ProjectCourseDomain> courseDomainRowMapper = new RowMapper<ProjectCourseDomain>() {

        @Override
        public ProjectCourseDomain mapRow(ResultSet rs, int rowNum) throws SQLException {

            ProjectCourseDomain domain = new ProjectCourseDomain();
            domain.setTemplateCourseId(rs.getLong("template_course_id"));
            domain.setCourseName(rs.getString("course_name"));
            return domain;
        }
    };

    public List<ProjectCourseDomain> findCourseByPostId(String postId) {
        String sql = "SELECT distinct tpc.template_course_id, tpc.course_name FROM t_project_course tpc LEFT JOIN t_project_post tpp ON tpc.project_id=tpp.project_id WHERE tpp.post_id= '" + postId + "' ORDER BY tpc.course_name ASC";
        return pageJdbcUtil.getInfo(sql, courseDomainRowMapper);
    }
}
